02. Spring Boot Template Engine - Thymeleaf

035ND C01 L03 A03 SPRINGBOOT WITH THYMELEAF INTRO

Instructions

  1. Goto https://start.spring.io/ and create a new spring boot project named spring-boot-thymeleaf with Thymeleaf and web as dependency.
  2. Download, unzip and import the project.
  3. Create a UserController under controller (need to create) directory.
@Controller
public class UserController {

   @RequestMapping("demo")
   public String demo(Model model) {
       model.addAttribute("message", "Hello Thymeleaf");
       // return to templates/demo.html page.
       return "demo";
   }
}

Create a demo.html under resources/template directory.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
   <meta charset="UTF-8">
   <title>Thymeleaft Demo</title>
</head>
<body>
   <span th:text="${message}"></span>
</body>
</html>

Run the application, and goto http://localhost:8080/demo, you should the “Hello Thymeleaf” printed on web page.

035ND C01 L03 A04 SPRINGBOOT WITH THYMELEAF

That’s our spring boot application using thymeleaf, easy right?

Compare to freemarker, it’s easier to use. One thing you need to add to your html header is xmlns:th="http://www.w3.org/1999/xhtml", which tells the html I am using thymeleaf engine. Let’s take a look at the thymeleaf syntax including

  • Variable
  • Condition
  • Loop